package cn.com.do1.component.console.helpMgr.ui;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.do1.common.annotation.struts.CatchException;
import cn.com.do1.common.annotation.struts.JSONOut;
import cn.com.do1.common.exception.BaseException;
import cn.com.do1.common.framebase.struts.BaseAction;

public class HelpMgrAction extends BaseAction{

	private final static transient Logger logger = LoggerFactory
			.getLogger(HelpMgrAction.class);
	private String help;
	
	@JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "保存成功", faileMsg = "保存失败"))
	public void save() throws Exception, BaseException {
		HttpServletRequest request = ServletActionContext.getRequest();
		String savePath = getHelpHtml(request);
		File file = new File(savePath);
		if(!file.exists())
			file.createNewFile();
		if(help != null){
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(help.getBytes("utf-8"));
			bos.close();
		}
	}

	private String getHelpHtml(HttpServletRequest request) {
		String savePath = request.getSession().getServletContext().getRealPath("/") + "help.html";
		return savePath;
	}
	
	@JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "加载成功", faileMsg = "加载失败"))
	public void load() throws IOException{
		File html = new File(this.getHelpHtml(ServletActionContext.getRequest()));
		StringBuilder sb = new StringBuilder();
		if(!html.exists()){
			html.createNewFile();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(html), "UTF-8"));
		String line = null;
		while ((line = br.readLine())!= null) {
			sb.append(line);
		}
		br.close();
		help = sb.toString();
		addJsonObj("help", help);// 注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
	}
	
	public String getHelp() {
		return help;
	}
	public void setHelp(String help) {
		this.help = help;
	}
	
	
	
	
}
